import {
    getAppointFreeStructure,
    getContainerSources,
    getStorageSources,
    WORKSTATE,
    workSwitch
} from "./public/CreepPublicAction.js";

/**
 * 运输者工作逻辑
 * @param {Creep} creep
 * @param sourcesIndex
 */
export const transporterRun = (creep, sourcesIndex) => {
    //工作逻辑转换
    workSwitch(creep, RESOURCE_ENERGY)
    if (creep.memory[WORKSTATE]) {
        workCore(creep)
    } else {
        getSources(creep, sourcesIndex)
    }

};

/**
 * 取完能量放回指定建筑
 * @param {Creep} creep
 */
const workCore = (creep) => {
    let firstTarget = getAppointFreeStructure(creep, STRUCTURE_EXTENSION, STRUCTURE_SPAWN, STRUCTURE_TOWER)
    if (firstTarget.length > 0) {
        if (creep.transfer(firstTarget[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
            creep.moveTo(firstTarget[0]);
        }
    } else {
        const factory = Game.rooms[creep.room.name].find(FIND_STRUCTURES, {filter: {structureType: STRUCTURE_FACTORY}})
        /**
         *
         * @type {Mineral}
         */
        const mineral = Game.getObjectById(Memory.Rooms[creep.room.name].mineral)
        if (factory.length > 0 && factory[0].store[RESOURCE_ENERGY] < 300 && factory[0].store[mineral.mineralType] > 500) {
            if (creep.transfer(factory[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
                creep.moveTo(factory[0]);
            }

        } else {
            const storage = creep.room.storage
            if (creep.transfer(storage, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
                creep.moveTo(storage);
            }
        }
    }
}
/**
 * 从container取能量
 * @param {Creep} creep
 * @param {number} sourcesIndex
 */
const getSources = (creep, sourcesIndex) => {
    const terminal = creep.room.terminal
    //存在terminal时且其中能量大于10000则从terminal中取能量
    if (terminal && terminal.store[RESOURCE_ENERGY] > 30000) {
        if (creep.withdraw(terminal, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
            creep.moveTo(terminal)
        }
    } else {
        if (!getContainerSources(creep, sourcesIndex, '#aeef06', 1300)) {
            getStorageSources(creep, sourcesIndex, '#aeef06', 0, true)
        }
    }

}